#include "header.h"
#include "server.h"

int lock;

int server_lock (void){
	char spid[8];
	int pid;

	lock = open ("/var/lock/aures.lock", O_RDWR | O_CREAT, 0640);
	if (lock < 0) return -1;
	if (lockf(lock, F_TLOCK, 0) < 0) return -1;
	
	pid = getpid();
	sprintf (spid, "%d", pid);
	write (lock, spid, strlen (spid));

	return (pid);
}

void server_unlock (void){
	close (lock);
	remove("/var/lock/aures.lock");
}

int server_halt (void){
	int file;
	char spid[8];

	file = open ("/var/lock/aures.lock", O_RDONLY);
	if (file < 0)
		return -1;

	if (read (file, spid, sizeof (spid)) > 0){
		int pid;
		close (file);
		if (sscanf (spid, "%d", &pid) == 1){
			kill (pid, SIGINT);
			return 0;
		}
	}

	close (file);
	return -1;
}

int server_restart (void){
	int file;
	char spid[8];

	file = open ("/var/lock/aures.lock", O_RDONLY);
	if (file < 0)
		return -1;

	if (read (file, spid, sizeof (spid)) > 0){
		int pid;
		close (file);
		if (sscanf (spid, "%d", &pid) == 1){
			kill (pid, SIGHUP);
			return 0;
		}
	}

	close (file);
	return -1;
}
